package com.neusoft.databus.sap.listener;

import java.util.stream.Collectors;

import javax.jms.ConnectionFactory;
import javax.jms.ObjectMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.common.bean.MessageBean;
import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.databus.common.bean.CommandBean;
import com.neusoft.databus.common.bean.SnmptrapBean;
import com.neusoft.databus.policy.service.MessageServie;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ConditionalOnClass({ConnectionFactory.class, ActiveMQConnectionFactory.class })
public class ActiveMqMessageListener {
    @Autowired
    private MessageServie messageServie;

    /**
     * 监听
     *
     * @param message
     */
    @JmsListener(destination = "${databus.policy.monitorDataTopic}")
    public void processMessage(ObjectMessage message) {
        try {
            final MessageBean messageBean = (MessageBean) message.getObject();
            final CommandBean commandBean = JsonUtils.jsonToPojo(messageBean.getMessage(), CommandBean.class);
            ActiveMqMessageListener.log.debug("receive message from activemq:{} ",
                    commandBean.getResourceBean().stream().map(it -> it.getCode()).collect(Collectors.joining(",")));
            this.messageServie.process(commandBean);
        } catch (final Exception e) {
            ActiveMqMessageListener.log.error("receive message from activemq exception:{}", e);
        } finally {
            message = null;
        }
    }

    @JmsListener(destination = "${databus.policy.snmpTrapTopic}")
    public void processTrapMessage(ObjectMessage message) {
        try {
            final MessageBean messageBean = (MessageBean) message.getObject();
            final SnmptrapBean snmptrapBean = JsonUtils.jsonToPojo(messageBean.getMessage(), SnmptrapBean.class);
            ActiveMqMessageListener.log.info("receive trapMessage from activemq:{} ", snmptrapBean.getResourceId());
            this.messageServie.processTrapMessage(snmptrapBean);
        } catch (final Exception e) {
            ActiveMqMessageListener.log.error("receive trapMessage from activemq exception:{}", e);
        } finally {
            message = null;
        }

    }
}
